const router = require('koa-router')()
const axios = require('axios')
const request = require('request')
const jwt = require('jsonwebtoken')

const AppId = 'wx2df109819424d2b1'
const Secret = '878c05b57da9c38ef76bbfd2c8b5717b'

// window.XMLHttpRequests

// 前缀
router.prefix('/api')

/**
 * 微信无感登陆 三方登陆
 * 小程序 -> koa2 -> 腾讯服务器
 * 1. 接收参数： code  wx.login->
 * 2. 拿到code 请求auth.code2Session接口
 */

const wxLoginFunc = requestUrl => {
  return new Promise((resolve, reject) => {
    request(requestUrl, (a, res) => {
      console.log('res:', res?.body)
      const response = JSON.parse(res?.body)
      if (response.errcode) {
        reject(response)
      } else {
        resolve(response)
      }
    })
  })
}

router.get('/get-test', async (ctx, next) => {
  ctx.body = {
    code: 0,
    msg: ctx.request.query
  }
})

router.post('/post-test', async (ctx, next) => {
  ctx.body = {
    code: 0,
    msg: { body: ctx.request.body }
  }
})

router.post('/login', async (ctx, next) => {
  // const { code } = ctx.request.body // 小程序的临时身份ID
  // ctx.body = { code }
  try {
    const { code } = ctx.request.body
    console.log('======>code:', code)
    const requestUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${AppId}&secret=${Secret}&js_code=${code}&grant_type=authorization_code`
    const response = await wxLoginFunc(requestUrl)
    // console.log('response============>:', response)
    // session_key openid
    const token = jwt.sign({ token: response.openid }, response.session_key, {
      expiresIn: '24h'
    })
    ctx.body = {
      code: 0,
      msg: 'success',
      data: { token }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: error
    }
  }
})

/**
 * @name accessToken 腾讯服务器访问令牌
 */
router.get('/getAccessToken', async (ctx, next) => {
  const requestUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${AppId}&secret=${Secret}`
  // axios
  //   .get(
  //     `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${AppId}&secret=${Secret}`
  //   )
  //   .then((res) => {
  //     console.log('res:', res)
  //   })

  try {
    const response = await wxLoginFunc(requestUrl)
    ctx.body = {
      code: 0,
      msg: 'success',
      data: { ...response }
    }
  } catch (error) {
    ctx.body = {
      code: 0,
      msg: error
    }
  }
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

module.exports = router
